import request from '@/utils/request'

export function additionDept(data) {
  return request({
    url: '/dept',
    method: 'post',
    data
  })
}

export function removeDept(id) {
  return request({
    url: `/dept/${id}`,
    method: 'delete'
  })
}

export function updateDept(data) {
  return request({
    url: '/dept',
    method: 'put',
    data
  })
}

export function searchDept(data, pageNum, pageSize) {
  return request({
    url: '/dept',
    method: 'get',
    params: Object.assign({}, data, { current: pageNum, size: pageSize })
  })
}

export function getDeptById(id) {
  return request({
    url: `/dept/${id}`,
    method: 'get'
  })
}

export function listAllDeptTree() {
  return new Promise((resolve, reject) => {
    request({
      url: 'dept/all',
      method: 'get'
    }).then(result => {
      const data = result.data.map(item => {
        const node = {}
        node.label = item.name
        node.value = item.id
        node.name = item.name
        node.id = item.id
        node.pid = item.parentId
        return node
      })
      resolve(structTree(data))
    })
  })
}

export function listDeptTree(deptId) {
  return new Promise((resolve, reject) => {
    request({
      url: 'dept/all',
      method: 'get'
    }).then(result => {
      const meatdata = result.data
      const resultList = []
      const _dept = deptId
      for (const k in meatdata) {
        if (_dept === meatdata[k].id) {
          resultList.push(meatdata[k])
        }
        for (const i in meatdata) {
          const node = meatdata[i]
          if (node.parentId === deptId) {
            resultList.push(node)
            deptId = node.id
            break
          }
        }
      }

      const data = resultList.map(item => {
        const node = {}
        node.label = item.name
        node.value = item.id
        node.name = item.name
        node.id = item.id
        node.pid = item.parentId
        return node
      })
      resolve(structTree(data))
    })
  })
}

const structTree = data => {
  const tree = []
  if (!Array.isArray(data)) {
    return tree
  }
  data.forEach(item => {
    delete item.children
  })
  const map = {}
  data.forEach(item => {
    map[item.id] = item
  })
  data.forEach(item => {
    const parent = map[item.pid]
    if (parent) {
      (parent.children || (parent.children = [])).push(item)
    } else {
      tree.push(item)
    }
  })
  return tree
}
